colors = Array('#aaaaaa','#aa0000','#008800','#0000aa','#888800','#008888','#880088','#000000');
colorshi = Array('#eeeeee','#aa5555','#558855','#5555aa','#888855','#558888','#885588','#000000');

default_width = 15;
default_height = 8;

var blacks = 0;
var cell_width = 0;
var cell_height = 0;

var user_id = -1;
var admin_mode = -1;
var author = -1;

var table_name = '';
var table_width = 0;
var table_height = 0;
var table_size = 0;

IE6 = 0;
UA = 1;
if (navigator.appVersion.indexOf("MSIE") != -1) { 
	UA = 0;

	temp = navigator.appVersion.split("MSIE");
	version = parseFloat(temp[1]);
	if (version < 7) IE6 = 1;
}

function init_creator() {	
	Tracker.getUserInfo(function(response) {
		var values = response.split(':'); 
		user_id = values[0];
		admin_mode = values[1];
		
		if (user_id == -1 || admin_mode == -1) {
			alert("Unable to authenticate user.  Please make sure you are logged in.");
			return;
		}
		
		process_table(0);
	});
}

function draw_table(divid, width, height)
{
	table_width = width;
   	table_height = height;
   	table_size = table_width * table_height;
   	
   	cell_size = 60;
   	cell_width = (document.body.clientWidth - cell_size) / width;
   	cell_height = cell_size;

   	if (cell_height < cell_width) cell_width = cell_height;
   	if (cell_width < cell_height) cell_height = cell_width;
   	
	adj_width = cell_width + 2 * UA;
	adj_height = cell_height + 2 * UA;
    document.getElementById(divid).style.width = table_width * adj_width + 4 + "px";
    document.getElementById(divid).style.height = table_height * adj_height + 4 + "px";

    var html_div = "";
    var colnum = 0;
    var rownum = 0;
    rainbow = [];
    blacks = 0;
    
    for (x = 0; x < table_size; x++)
    {
    	rainbow[x] = 1;
        if (colnum >= table_width) { colnum = 0; rownum++; }
        celltop = rownum * adj_height + 2 * UA;
        cellleft = colnum * adj_width + 2 * UA;
		html_div += '<div onClick="wowza(\'' + x +'\')" id="' + x + '" style="float: left; cursor: pointer; width:' + cell_width + 'px; ' + 
			'left:' + cellleft + 'px; top:' + celltop + 'px; height:' + cell_height + 'px; ' + 
			'text-decoration:none; font-family:verdana;font-size:' + eval(parseInt(Math.min(cell_width, cell_height) / 2)) + 'px; ' +
			'z-index: 2; -moz-user-select: none; background-color: #aaa; border: solid; border-width: 1px">&nbsp</div>';
       	colnum++;
    }
    
    document.getElementById(divid).innerHTML = html_div;
    document.getElementById("blackp").value = 0;
    
    document.getElementById('delete_button').disabled = false;
	document.getElementById('save_button').disabled = false;
}

function wowza(x) {
	if (x < 0 || x >= table_size)
		return;

  	if (rainbow[x] == 0) {
		document.getElementById(x).style.backgroundColor = '#aaaaaa';
		rainbow[x] = 1;
		blacks--;
  	} else {
		document.getElementById(x).style.backgroundColor = '#000000';
		rainbow[x] = 0;
		blacks++;
	}
	
	document.getElementById("blackp").value = blacks * 100 / table_size;
}

function set_parameters() {
	table_name = document.getElementById('table_name').value;
	table_width = document.getElementById('table_width').value;
	table_height = document.getElementById('table_height').value;
	attack_style = document.getElementById('attack_style').options.selectedIndex;
	start_areas = document.getElementById('start_areas').value;
	start_dice = document.getElementById('start_dice').value;
	dice_cap = document.getElementById('dice_cap').value;
	max_roll = document.getElementById('max_roll').value;
	percent_areas = document.getElementById('%_areas').value;
	percent_dice = document.getElementById('%_dice').value;
}

function process_table(index) {
	if (index == 0) {
		document.getElementById('table_name').value = '';
		document.getElementById('table_width').value = default_width;
		document.getElementById('table_height').value = default_height;
		document.getElementById('attack_style').options.selectedIndex = 0;
		document.getElementById('start_areas').value = 0;
		document.getElementById('start_dice').value = 0;
		document.getElementById('dice_cap').value = 0;
		document.getElementById('%_areas').value = 0.0;
		document.getElementById('%_dice').value = 0.0;
		document.getElementById('max_roll').value = 0;
		
		author = user_id;
		
		document.getElementById('tables').options.selectedIndex = 0;
		
		draw_table('usertable', default_width, default_height);
	}
	else {
		var values;
		
		if (index == -1) {
			document.getElementById('tables').options.selectedIndex = 0;
			user_data = '|' + document.getElementById('user_data').value;
			values = user_data.split("|");
		}
		else
			values = document.getElementById('tables').options[index].value.split("|");
	
		author = values[0];
		document.getElementById('table_name').value = values[1];
		document.getElementById('table_width').value = values[2];
		document.getElementById('table_height').value = values[3];
		document.getElementById('attack_style').options.selectedIndex = values[4];
		document.getElementById('start_areas').value = values[5];
		document.getElementById('start_dice').value = values[6];
		document.getElementById('dice_cap').value = values[7];
		document.getElementById('%_areas').value = values[8];
		document.getElementById('%_dice').value = values[9];
		document.getElementById('max_roll').value = values[10];
		
		draw_table('usertable', values[2], values[3]);
		
		var squares = values[11].split(",");
		for (i = 0; i < squares.length; i++)
			if (squares[i] == '0')
				wowza(i);
		
		if (admin_mode <= 10 && author != user_id) {
			document.getElementById('delete_button').disabled = true;
			document.getElementById('save_button').disabled = true;
		}
	}
	
	set_parameters();
}

function load_tables() { 
	check_boxes_values = document.getElementById('author_only_tables').checked + ':' + document.getElementById('unapproved').checked;
	Tracker.getTables( check_boxes_values, {
		callback:function(str) {
			if (str == null)
				alert("Unable to retrieve user tables.  Please make sure you are logged in.");
			else {
				// Reset the list
				var tables = document.getElementById('tables');
				tables.options.length = 1;
				
				if (str.length > 1) {
					var values1 = str.split(";");
				
					// Add table names
					for (i = 0; i < values1.length; i++) {
						var values2 = values1[i].split(":");
						// Set value to be the concatanated string of parameters
						tables.options[tables.options.length] = new Option(values2[0] + ': ' + values2[1], values2[2]);
					}
				}
			}
		}
	});
}

function save_table() {
	// Prepare values
	set_parameters();
	
	// Check values
	if (table_name == '')
		alert('Table name is empty.  Please name the table.');
	else if (table_name.indexOf(";") >= 0 || table_name.indexOf("\\") >= 0 ||
				table_name.indexOf("/") >= 0 || table_name.indexOf("\"") >= 0 ||
				table_name.indexOf("\'") >= 0 || table_name.indexOf(":") >= 0)
		alert('Table name contains a restricted character (one of ;, \, /, \", \', :)'); 
	else if (table_width <= 0)
		alert('Table width must be greater than 0');
	else if (table_height <= 0)
		alert('Table height must be greater than 0');
	else if (table_width > 26)
		alert('Table width must be no greater than 26');
	else if (table_height > 22)
		alert('Table height must be no greater than 22');
	else if (start_areas <= 0)
		alert('Starting areas must be greater than 0');
	else if (start_areas > 10)
		alert('Starting areas must be no greater than 10');
	else if (start_areas - start_dice >= 0)
		alert('Starting areas must be less than dice');
	else if (start_dice <= 0)
		alert('Starting dice must be greater than 0');
	else if (start_dice > 40)
		alert('Starting dice must be no greater than 40');
	else if (dice_cap <= 0)
		alert('Dice cap per square must be greater than 0');
	else if (dice_cap > 10)
		alert('Dice cap per square must be no greater than 10');
	else if (max_roll <= 0)
		alert('Maximum roll per dice must be greater than 0');
	else if (max_roll > 10)
		alert('Maximum roll per dice must be no greater than 10');
	else if (percent_areas < 0.00 || percent_areas > 1.00)
		alert('Percent of areas allowed to move during offturn must be between 0.00 and 1.00');
	else if (percent_dice < 0.00 || percent_dice > 1.00)
		alert('Percent of square moved during offturn movement must be between 0.00 and 1.00');
	else {
		Tracker.saveTable(author, table_name, table_height, table_width, attack_style, start_areas, start_dice, dice_cap,
			max_roll, percent_areas, percent_dice, rainbow.join(), 
			function(response) {
				if (response == "false")
					alert("Unable to save table");
				else {
					// Reload list of tables in case a new table was added
					load_tables();
				}
			});
	}
}

function delete_table() {
	var tables = document.getElementById('tables');
	var selection = tables.options.selectedIndex;
	
	if (selection == 0)
		return;
		
	var answer = confirm("Are you sure you want to delete table '" + tables.options[selection].text + "' ?");
	
	if (answer)
	{
		// Delete selected table
		Tracker.deleteTable(table_name, author, function(response) {
			if (response == "false")
				alert("Unable to delete table");
			else {
				// Reload list of tables
				load_tables();
				// Reset table
				process_table(0);
			}
		} );
	}
}

function xstooltip_findPosX(obj) 
{
  var curleft = 0;
  if (obj.offsetParent) 
  {
    while (obj.offsetParent) 
        {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}

function xstooltip_findPosY(obj) 
{
    var curtop = 0;
    if (obj.offsetParent) 
    {
        while (obj.offsetParent) 
        {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}

function xstooltip_show(tooltipId, parentId, posX, posY)
{
    it = document.getElementById(tooltipId);
    
    if ((it.style.top == '' || it.style.top == 0) 
        && (it.style.left == '' || it.style.left == 0))
    {
        // need to fixate default size (MSIE problem)
        it.style.width = it.offsetWidth + 'px';
        it.style.height = it.offsetHeight + 'px';
        
        img = document.getElementById(parentId); 
    
        // if tooltip is too wide, shift left to be within parent 
        if (posX + it.offsetWidth > img.offsetWidth) posX = img.offsetWidth - it.offsetWidth;
        if (posX < 0 ) posX = 0; 
        
        x = xstooltip_findPosX(img) + posX;
        y = xstooltip_findPosY(img) + posY;
        
        it.style.top = y + 'px';
        it.style.left = x + 'px';
    }
    
    it.style.visibility = 'visible'; 
}

function xstooltip_hide(id)
{
    it = document.getElementById(id); 
    it.style.visibility = 'hidden'; 
}